package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"perm-guard/cache"
	"perm-guard/models"
	"strconv"
	"time"
)

func CarConList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))

	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	Offset := (page - 1) * size
	/*
		     SELECT
			  car_contents.cid as ConId,
			  car_cons.car_no as CarNo,
			  car_cons.car_name as CarName,
			  car_cons.car_code as CarCode,
			  car_contents.con_code as ConCode,
			  car_contents.con_name as ConName
			FROM
			  car_contents
			  LEFT JOIN car_cons ON car_contents.cid = car_cons.id
	*/
	var list []models.CarContentList
	redis_key := "carCon" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("car_contents").
			Select(
				"car_contents.cid as ConId",
				"car_cons.car_no as CarNo",
				"car_cons.car_name as CarName",
				"car_cons.car_code as CarCode",
				"car_contents.con_code as ConCode",
				"car_contents.con_name as ConName",
			).
			Joins("LEFT JOIN car_cons ON car_contents.cid = car_cons.id").
			Offset(Offset).
			Limit(size).
			Debug().
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	var total int64
	models.DB.Model(&models.CarContent{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"list":  list,
		"total": total,
	})
	return
}
func CarConDetail(c *gin.Context) {
	id := c.Query("id")
	var list models.CarContentList
	redis_key := "cardetail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		models.DB.Table("car_contents").
			Select(
				"car_contents.cid as ConId",
				"car_cons.car_no as CarNo",
				"car_cons.car_name as CarName",
				"car_cons.car_code as CarCode",
				"car_contents.con_code as ConCode",
				"car_contents.con_name as ConName",
			).
			Joins("LEFT JOIN car_cons ON car_contents.cid = car_cons.id").
			Where("car_contents.id", id).
			Debug().
			Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": list,
	})
	return
}
